package com.yitiao.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

//@Configuration
public class MultiDataSource {

    public static final String MASTER_DATA_SOURCE = "masterDataSource";
    public static final String SALVE_ZERO_DATA_SOURCE = "salve0DataSource";
    public static final String SALVE_ONE_DATA_SOURCE = "salve1DataSource";


    @Bean(name = MultiDataSource.MASTER_DATA_SOURCE)
    @ConfigurationProperties(prefix = "datasource.master")
    public DataSource masterDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = MultiDataSource.SALVE_ONE_DATA_SOURCE)
    @ConfigurationProperties(prefix = "datasource.salve1")
    public DataSource salveOneSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = MultiDataSource.SALVE_ZERO_DATA_SOURCE)
    @ConfigurationProperties(prefix = "datasource.salve0")
    public DataSource salveZeroSource() {
        return DataSourceBuilder.create().build();
    }

    @Primary
    @Bean(name = "dataSourceHandler")
    public DataSourceHandler dataSource() {
        DataSourceHandler dynamicDataSource = new DataSourceHandler();
        dynamicDataSource.setDefaultTargetDataSource(masterDataSource());
        Map<Object, Object> dataSourceMap = new HashMap<>(4);
        dataSourceMap.put(MASTER_DATA_SOURCE, masterDataSource());
        dataSourceMap.put(SALVE_ZERO_DATA_SOURCE, salveZeroSource());
        dataSourceMap.put(SALVE_ONE_DATA_SOURCE, salveOneSource());

        dynamicDataSource.setTargetDataSources(dataSourceMap);
        return dynamicDataSource;
    }
}
